# -*- coding: utf-8 -*-

import os

from hbcxx.fileutils import *
from hbcxx.cxx_format import CXX_INCLUDES


def simcxx_get_filename(source_path: str):
    # Extract the file name.
    _, filename = os.path.split(source_path)
    # Get the extension name.
    _, extname = os.path.splitext(source_path)
    # Remove the extname from the filename.
    return filename[:-len(extname)]


def simcxx_dump_header(header_name: str, header_path: str, header_file: list):
    # Get the header files.
    include_text = '\n'.join('#include {}'.format(x) for x in list(CXX_INCLUDES))
    # Create the macro name.
    cap_filename = header_name.upper()
    # Construct the header macro.
    header_texts = ['#ifndef {}_H'.format(cap_filename),
                     '#define {}_H'.format(cap_filename),
                     '',
                     include_text,
                     '',
                     '\n\n'.join(header_file),
                     '',
                     '#endif // {}_H'.format(cap_filename)]
    header_texts = '\n'.join(header_texts)
    # Open the output file path.
    create_output_path(header_path)
    # Output the file.
    header_filepath = os.path.join(header_path, header_name + '.h')
    with open(header_filepath, 'w') as file:
        file.write(header_texts)


def simcxx_dump_cpp(cpp_name: str, cpp_path: str, cpp_file: list):
    # Check the cpp file information.
    if len(cpp_file) == 0:
        # No need to dump cpp file.
        return
    # Construct the cpp file.
    # First, it needs to include the same file name of the header.
    cpp_texts = ['#include "{}.h"'.format(cpp_name),
                 "",
                 '\n\n'.join(cpp_file)]
    cpp_texts = '\n'.join(cpp_texts)
    # Open the output file path.
    cpp_filepath = os.path.join(cpp_path, cpp_name + '.cpp')
    with open(cpp_filepath, 'w') as file:
        file.write(cpp_texts)
